//
// Created by haoy on 2017/3/10.
//

#ifndef RECORD_RTP_WRITER_HPP
#define RECORD_RTP_WRITER_HPP

#include <string>

#include "dbg.hpp"
#include "mod/rtp.h"
#include "packet.hpp"
#include "packet_reorder.hpp"
#include "rav_record.h"
#include "tlv.hpp"
#include "util.h"

#include "xvideo_util.hpp"
#include "media_probe.hpp"


class RTPWriter : public PacketHandler {
    // set this false to fallback to receiving time as pts
    bool _use_ntp_as_pts = true;
public:
    RTPWriter();
    ~RTPWriter();

    RTPWriter& video(const mediacodec_id_t codec, const uint32_t width, const uint32_t height, const uint32_t fps);
    RTPWriter& audio(const mediacodec_id_t codec, const uint32_t sample_rate, const uint32_t channels);
    void output(const std::string& filename);
    void writeMediaInfo();
    void close();

private:
    void onCodecRegistry(CodecRegistry& codecs, uint32_t pt, const std::string& codec_name) override;
    void onAudioPacket(RTPPacket* packet, uint64_t pts) override;
    void onVideoPacket(RTPPacket* packet, uint64_t pts) override;

private:
    // FILE* fp_ = nullptr;
    std::string _output_file;            // /root/rtc/recorder/tmp/rtc-50710
    std::string _media_file;                // /root/rtc/recorder/tmp/rtc-50710.mkv
    media_probe _media_pb;
    XVBuffer* _buffer = nullptr;

    RTPDepacketizer* _video_depacketizer;

    PacketReorder<RTPPacket> _audio_reorder;
    PacketReorder<RTPPacket> _video_reorder;

    bool _has_video;
    mediacodec_id_t _video_codec;
    uint32_t _video_width;
    uint32_t _video_height;
    uint32_t _video_fps;

    bool _has_audio;
    mediacodec_id_t _audio_codec;
    uint32_t _audio_sample_rate;
    uint32_t _audio_channels;

    ravrecord_t _recorder;
    RTPMap _rtp_map;

    int64_t _begin_ts = -1;
    std::string _ts_file_name;

    uint64_t _audio_last_pts = 0;
    uint32_t _audio_last_ts = 0;
    uint64_t _video_last_pts = 0;
    uint32_t _video_last_ts = 0;
    int _video_last_seq = -1;
    uint16_t _video_last_cycles = 0;
    bool _drop_mod = true;
    // bool _video_last_seq_set = false;

    uint64_t _video_frame_count = 0;
    uint64_t _audio_frame_count = 0;

    std::vector<RTPPacket*> _sps_pps_cache;
};

#endif //RECORD_RTP_WRITER_HPP
